<!-- ERC-知识库-故障库页面 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterText" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTree('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTree('open')" />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
          </px-tooltip>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRef"
            :data="treeData"
            :props="{ children: 'children', label: 'name' }"
            :filter-node-method="filterNode"
            node-key="id"
            :expand-on-click-node="false"
            default-expand-all
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClick"
          />
        </px-scrollbar>
      </div>
      <div class="equip-table-wrap">
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="8">
              <px-form-item label="故障名称">
                <px-input
                  v-model="queryParams.faultTypeName"
                  placeholder="请输入故障名称"
                  maxlength="50"
                  clearable
                  @blur="queryParams.faultTypeName = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-form-item label="工单完成时间" prop="completionTime">
                <px-select
                  v-model="queryParams.completionTime"
                  placeholder="请选择工单完成时间"
                  clearable
                  filterable
                  @clear="queryParams.completionTime = 'PAST'"
                >
                  <px-option v-for="item in finishTimeList" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <div class="equip-table-btn">
          <px-button v-has="'ERC_LEARN_FAULT_ADD'" style="margin-right: 8px" type="primary" :disabled="isEqpCode" @click="addBtn">
            新增故障经验
          </px-button>
        </div>
        <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 304px)" border>
          <px-table-column label="序号" width="80" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.type === 'case'" #default="scope">
              <template v-if="scope.row.workOrders && scope.row.workOrders.length === 0">-</template>
              <template v-else>
                <px-tooltip v-for="order in scope.row.workOrders" :key="order.workOrderId" :content="order.workOrderName">
                  <!-- <div class="order-tag" @click="handleToMaintain(order)">{{ order.workOrderName }}</div> -->
                  <px-tag @click="handleToMaintain(order)">{{ order.workOrderName || "-" }}</px-tag>
                </px-tooltip>
              </template>
            </template>
            <template v-else #default="scope">
              <px-button v-if="item.workOrderCode && scope.row.workOrderCode" link type="primary" @click="handleToMaintain(scope.row)">
                {{ scope.row.workOrderCode }}
              </px-button>
              <div v-else-if="item.workOrderCode && !scope.row.workOrderCode">-</div>
              <px-button v-else-if="item.workOrderCount && scope.row.workOrderCount" link type="primary" @click="handleViewNum(scope.row)">
                {{ scope.row.workOrderCount }}
              </px-button>
              <span v-else-if="item.workOrderCount && !scope.row.workOrderCount">-</span>
              <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" width="100" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ERC_LEARN_FAULT_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ERC_LEARN_FAULT_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 新增/编辑页面 -->
    <AddDialog
      :dialogVisible="dialogVisible"
      :dialogType="dialogType"
      :dialogRow="dialogRow"
      :eqpCode="eqpCode"
      :faultTypeCode="faultTypeCode"
      @closeDialog="dialogVisible = false"
      @queryTable="queryTable"
    />
    <!-- 查看页面 -->
    <ViewDialog
      :dialogVisible="numDialogVisible"
      :faultTypeCode="faultTypeCode"
      :startTime="startTime"
      :endTime="endTime"
      :tableData="workOrderKnowledgeUseDTOS"
      :workOrderIds="workOrderIds"
      @closeDialog="handleCloseDialog"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_LEARN_FAULT"
});
import { deleteFaultManage, queryFaultManage } from "@/api/erc/learn";
import { queryEquipTypeTree } from "@/api/erc/spareParts";
import dayjs from "dayjs";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import AddDialog from "./components/AddDialog.vue";
import ViewDialog from "./components/ViewDialog.vue";

const router = useRouter();
const state = reactive<any>({
  filterText: "",
  treeRef: null,
  treeData: [],
  expandedKeys: [],
  isTreeOpen: true,
  isEqpCode: true,
  eqpCode: "",
  faultTypeCode: "",
  startTime: "",
  endTime: "",
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    eqpCodes: [],
    faultTypeName: "",
    completionTime: "PAST"
  },
  tableColumns: [
    { prop: "faultTypeName", label: "故障名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
    // { prop: "startTime", label: "故障统计开始时间", minWidth: "160", showOverflowTooltip: true },
    // { prop: "endTime", label: "故障统计结束时间", minWidth: "160", showOverflowTooltip: true },
    { prop: "workOrderCode", label: "故障维修案例", minWidth: "220", showOverflowTooltip: false, type: "case" },
    { prop: "workOrderCount", label: "维修工单数量", minWidth: "110", showOverflowTooltip: true, workOrderCount: true },
    { prop: "createByName", label: "创建人", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  workOrderKnowledgeUseDTOS: [],
  total: 0,
  dialogVisible: false,
  dialogType: "add",
  dialogRow: {},
  numDialogVisible: false,
  finishTimeList: [
    {
      label: "全部",
      value: "ALL"
    },
    {
      label: "过去一年",
      value: "PAST"
    }
  ],
  workOrderIds: []
});
const {
  filterText,
  treeRef,
  treeData,
  expandedKeys,
  isTreeOpen,
  isEqpCode,
  eqpCode,
  faultTypeCode,
  startTime,
  endTime,
  queryParams,
  tableColumns,
  tableData,
  total,
  dialogVisible,
  dialogType,
  dialogRow,
  numDialogVisible,
  finishTimeList,
  workOrderKnowledgeUseDTOS,
  workOrderIds
} = toRefs(state);

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

// 进入页面时触发
onMounted(() => {
  const current = dayjs().year();
  for (let start = current; start >= 2024; start--) {
    finishTimeList.value.push({
      label: `${start}年`,
      value: start
    });
  }
  queryTree();
  queryTable();
});
const handleCloseDialog = () => {
  numDialogVisible.value = false;
  workOrderIds.value = [];
  workOrderKnowledgeUseDTOS.value;
};
/** 左侧-树形区 **/
// 查询左侧树
const queryTree = async () => {
  const params = {
    name: ""
  };
  const data: any = await queryEquipTypeTree(params);
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  filterText.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value.eqpCodes = [];
  isEqpCode.value = true;
  queryTable();
};
// 点击左侧树节点，获取facCode，查询设备列表
const nodeClick = e1emData => {
  if (e1emData.code === "0") {
    queryParams.value.eqpCodes = [];
  } else {
    const codes = [e1emData.code];
    if (e1emData.children && e1emData.children.length > 0) {
      e1emData.children.forEach(item => {
        codes.push(item.code);
      });
    }
    queryParams.value.eqpCodes = codes;
  }
  if ((e1emData?.typeLevel === 2 && !e1emData?.children) || e1emData?.typeLevel === 3) {
    eqpCode.value = e1emData.code;
    isEqpCode.value = false;
  } else {
    isEqpCode.value = true;
  }
  queryTable();
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};

/** 右侧-表格区 **/
// 查询备件台账列表
const queryTable = async () => {
  const params = queryParams.value;
  const data = await queryFaultManage(params);
  tableData.value = data?.data;
  total.value = data?.total;
};
// 重置筛选条件和备件台账列表
const resetTable = async () => {
  queryParams.value.faultTypeName = "";
  queryParams.value.completionTime = "PAST";
  queryTable();
};
// 新增备件台账按钮
const addBtn = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
};
// 编辑
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  dialogRow.value = row;
  eqpCode.value = row.eqpCode;
  dialogVisible.value = true;
};
// 跳转到维修详情
const handleToMaintain = (row: any) => {
  router.push(`/erc/maintain/detail?id=${row.workOrderId}`);
};
// 查看
const handleViewNum = (row: any) => {
  faultTypeCode.value = row?.faultTypeCode;
  startTime.value = row?.startTime;
  endTime.value = row?.endTime;
  workOrderKnowledgeUseDTOS.value = row?.workOrderKnowledgeUseDTOS;
  workOrderIds.value = row?.workOrders?.map(item => item.workOrderId);
  numDialogVisible.value = true;
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前故障经验“${row.faultTypeName}”吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteFaultManage({
        id: row.id
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");

.order-tag {
  box-sizing: border-box;
  display: inline-flex;
  height: 24px;
  padding: 0 9px;
  overflow: hidden;
  color: #3b82f6;
  text-overflow: ellipsis;
  text-wrap: nowrap;
  cursor: pointer;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;

  &:not(:last-child) {
    margin-bottom: 5px;
  }
}

:deep(.px-tag) {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
